package com.ankicoo.database.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.ankicoo.database.service.DataBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.Table;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ankicoo.common.constant.CommConst.DATETIME_FORMAT;

/**
 * Description: 数据存取器
 *
 * @author : QCYANG
 * @date : 2021/11/17 10:36
 */
@Service
public class DataBaseServiceImpl implements DataBaseService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public <T>List<T> selectAll(Class<T> classType){
        String tableName = classType.getAnnotation(Table.class).name();
        String sql = "select * from " + tableName;
        return selectList(classType,sql);
    }


    @Override
    public <T>List<T> selectList(Class<T> classType, String sql){
        List<Map<String, Object>> resultMap = selectListMap(sql);
        return resultMap.stream().map(item -> BeanUtil.toBean(item, classType)).collect(Collectors.toList());
    }

    @Override
    public <T>List<T> selectList(Class<T> classType, String sql, Map<String, Object> params){
        List<Map<String, Object>> resultMap = selectListMap(sql,params);
        return resultMap.stream().map(item -> BeanUtil.toBean(item, classType)).collect(Collectors.toList());
    }

    @Override
    public List<Map<String, Object>> selectListMap(String sql){
        return jdbcTemplate.queryForList(sql);
    }

    @Override
    public List<Map<String, Object>> selectListMap(String sql, Map<String, Object> params){
        return jdbcTemplate.queryForList(analysisParams(sql,params));
    }

    private static String analysisParams(String sql, Map<String, Object> params){
        for(String key: params.keySet()){
            if (sql.contains(":"+key)){
                sql = sql.replaceAll(":"+key,"'"+param2String(params.get(key))+"'");
            }
        }
        return sql;
    }

    private static String param2String(Object param){
        if (param instanceof Date){
            return DateUtil.format((Date)param ,DATETIME_FORMAT);
        }else {
            return param.toString();
        }
    }

}
